<template>
  <div class="content flex flex-col">
    <div class="flex-1 overflow-y-auto">
      <!-- 初始欢迎信息 -->
      <WelcomeMessage v-if="!chatMessages.length" @quick-questions="handleQuickQuestions" />

      <!-- 聊天消息列表 -->
      <MessageList v-else :messages="chatMessages" ref="messageListRef" />
    </div>

    <!-- 输入框和发送按钮 -->
    <MessageInput
      :models="models"
      :processing="processing"
      :is-login="isAuthenticated"
      :show-new-conversation-button="chatMessages.length > 0"
      @send-message="handleSendMessage"
      @create-new-conversation="createNewConversation"
      @stop-processing="stopProcessing"
      @model-change="handleModelChange"
    />

    <div class="mt-3 text-center text-sm text-gray-400">以上内容由AI生成，仅供参考和借鉴</div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import WelcomeMessage from './WelcomeMessage.vue'
import MessageList from './MessageList.vue'
import MessageInput from './MessageInput.vue'
import { useChatService } from '@/composables/useChatService'
import type { ChatMessage, ChatProps, ChatEmits } from '@/types/chat'
import { useUserStore } from '@/stores/user'
import { useHistoryStore } from '@/stores/history'

// import quickQuestions from './quickQuestions'

// Props和Emits
const props = withDefaults(defineProps<ChatProps>(), {
  data: undefined,
})

const emit = defineEmits<ChatEmits>()

// 使用聊天服务
const { processing, models, sendToAI, stopProcessing, checkSensitiveWords } = useChatService()

// 用户状态
const userStore = useUserStore()
const { isAuthenticated } = storeToRefs(userStore)

// 历史记录状态
const historyStore = useHistoryStore()

const deepseek = ref(null)

// 聊天消息列表
const chatMessages = ref<ChatMessage[]>([])
const messageListRef = ref()
const currentModel = ref('sydyznt')

// 会话ID
let sessionId = props.data || ''

// 初始化会话信息
const initialMessages = async (sessionId?: string) => {
  chatMessages.value = []

  // 首先检查 historyStore 中是否有当前历史记录
  if (historyStore.currentHistory.length > 0) {
    // 从 historyStore 的 currentHistory 中加载消息
    chatMessages.value = historyStore.currentHistory.map((item: any) => ({
      content: item.content,
      sender: Number(item.sender) === 1 || item.sender === 'chat' ? 'chat' : 'user',
      time: item.timestamp || item.timestamp || item.time || Date.now(),
      images: item.images,
    }))
  } else if (sessionId) {
    // 如果没有当前历史记录但有 sessionId，则加载
    try {
      const historyMessages = await historyStore.initChatFromHistory(sessionId)
      if (historyMessages && Array.isArray(historyMessages)) {
        chatMessages.value = historyMessages.map((item: any) => ({
          content: item.content,
          sender: Number(item.sender) === 1 || item.sender === 'chat' ? 'chat' : 'user',
          time: item.timestamp || item.timestamp || item.time || Date.now(),
          images: item.images,
        }))
      }
    } catch (error) {
      ElMessage.error('加载历史记录失败')
    }
  }
}

// 新增对话
const createNewConversation = async () => {
  sessionId = ''
  // 清空当前历史记录
  historyStore.clearCurrentHistory()

  const welcomeMessage: ChatMessage = {
    content: '你好，我是桉树人工林垂类模型，你可以问我任何问题，比如：',
    sender: 'chat',
    timestamp: Date.now(),
  }
  chatMessages.value = [welcomeMessage]

  try {
    // 使用历史记录 store 保存消息
    sessionId = await historyStore.saveMessage(welcomeMessage)
  } catch (error) {
    console.error('保存欢迎消息失败:', error)
  }
}

// 快捷提问
const handleQuickQuestions = (e: any) => {
  // 创建用户消息
  // const userMessage: ChatMessage = {
  //   content: e.title,
  //   sender: 'user',
  //   timestamp: Date.now(),
  //   images: [],
  // }
  // chatMessages.value.push(userMessage)
  // const item = quickQuestions.find(quickQuestion => quickQuestion.title === e.title);
  // if (item) {
  //   chatMessages.value.push({
  //     content: item.description,
  //     sender: 'chat',
  //     timestamp: Date.now()
  //   })
  // }
  handleSendMessage({
    message: e.title,
    images: []
  })
}

// 处理发送消息
const handleSendMessage = async (data: { message: string; images: any[] }) => {
  if (!isAuthenticated.value) {
    const res = await userStore.login()
    if (!res) {
      return
    }
  }

  if (!data.message.trim() && data.images.length === 0) {
    ElMessage.warning('请输入内容或上传图片')
    return
  }

  // 检查敏感词
  if (data.message.trim()) {
    const hasSensitiveWords = await checkSensitiveWords(data.message)
    if (hasSensitiveWords) {
      ElMessage.warning('输入框有敏感内容，请重新输入')
      return
    }
  }

  // 创建用户消息
  const userMessage: ChatMessage = {
    content: data.message,
    sender: 'user',
    timestamp: Date.now(),
    images: data.images.length > 0 ? data.images : undefined,
  }

  chatMessages.value.push(userMessage)

  try {
    // 使用历史记录 store 保存用户消息
    const sessionId1 = await historyStore.saveMessage(userMessage)
    if (sessionId1) {
      sessionId = sessionId1
    }
    // 发送到AI (目前AI可能不支持图片，但我们先发送文本部分)
    if (data.message.trim()) {
      await sendToAI(
        data.message,
        currentModel.value,
        chatMessages.value,
        sessionId,
        deepseek.value,
        // 传递保存消息的回调函数
        async (aiMessage: ChatMessage) => {
          const newSessionId = await historyStore.saveMessage(aiMessage)
          if (newSessionId) {
            sessionId = newSessionId
          }
        },
      )
    } else if (data.images.length > 0) {
      // 如果只有图片没有文字，可以发送一个默认提示
      await sendToAI(
        '请分析这张图片',
        currentModel.value,
        chatMessages.value,
        sessionId,
        deepseek.value,
        async (aiMessage: ChatMessage) => {
          const newSessionId = await historyStore.saveMessage(aiMessage)
          if (newSessionId) {
            sessionId = newSessionId
          }
        },
      )
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
  }
}

// 处理模型变化
const handleModelChange = (model: string) => {
  currentModel.value = model
}

// 监听 historyStore 的 currentHistory 变化
watch(
  () => historyStore.currentHistory,
  () => {
    initialMessages()
  },
  { deep: true, immediate: true },
)

// 监听 props.data 变化
watch(
  () => props.data,
  (newVal) => {
    if (newVal && newVal !== sessionId) {
      sessionId = newVal
      initialMessages(sessionId)
    }
  },
  { immediate: true },
)

onMounted(() => {
  initialMessages()
})
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  min-width: 600px;
  margin: 0 auto;
  height: 100%;
  padding: 40px 80px;
}
</style>
